<template>
  <el-form ref="formRef" :model="form" label-width="120px">
    <el-form-item prop="name" label="商品名称" style="width: 92%">
      <el-input v-model="form.name" placeholder="请填写商品名称" />
    </el-form-item>

    <el-form-item label="分类名称" prop="categoryId" style="width: 50%">
      <el-select v-model="form.categoryId" placeholder="请选择二级分类名称">
        <el-option-group
          v-for="category in categoryList"
          :key="category.id"
          :label="category.name"
        >
          <el-option
            v-for="item in category.children"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-option-group>
      </el-select>
    </el-form-item>

    <el-form-item prop="price" label="商品价格" style="width: 92%">
      <el-input v-model="form.price" placeholder="请填写商品价格" />
    </el-form-item>

    <el-form-item label="商品图片">
      <el-upload
        ref="uploadRef"
        class="upload-demo"
        v-model:file-list="fileList"
        :on-exceed="handleExceed"
        :on-success="uploadSuccess"
        :limit="1"
        :action="uploadURL"
        :headers="{ jwt: token }"
        :data="{ type: 'goods_picture' }"
        :show-file-list="true"
      >
        <template #trigger>
          <el-button type="primary">请选择图片</el-button>
        </template>
        <template #tip>
          <div class="el-upload__tip">图片文件大小不超过500KB</div>
        </template>
      </el-upload>
    </el-form-item>

    <el-form-item label="商品相册" prop="albumList">
      <el-upload
        ref="uploadAlbumRef"
        class="upload-demo"
        v-model:file-list="albumFileList"
        list-type="picture-card"
        :headers="{ jwt: token }"
        :action="uploadURL"
        :on-preview="albumHandlePreview"
        :on-success="uploadAlbumSuccess"
        :multiple="true"
        :on-remove="albumHandleRemove"
        :data="{ type: 'goods_album' }"
      >
        <el-icon><Plus /></el-icon>
      </el-upload>
      <el-dialog v-model="albumDialogVisible" align-center width="30%">
        <el-image :src="albumDialogImageUrl" />
      </el-dialog>
    </el-form-item>

    <el-form-item prop="stock" label="商品库存" style="width: 92%">
      <el-input v-model="form.stock" placeholder="请填写商品库存" />
    </el-form-item>

    <el-form-item prop="spec" label="商品规格" style="width: 92%">
      <el-input v-model="form.spec" placeholder="请填写商品规格" />
    </el-form-item>

    <el-form-item
      label="商品简介"
      prop="description"
      style="width: 92%"
      class="desc"
    >
      <Editor :init="initEditor" v-model="form.description"></Editor>
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="editSubmit" v-if="id">修改</el-button>
      <el-button type="primary" @click="addSubmit" v-else>新增</el-button>
      <el-button @click="btnCancel">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import Editor from "@tinymce/tinymce-vue";
import {
  getCategoryList,
  getGoods,
  editGoods,
  uploadPictureURL,
  addGoods,
} from "../api/api";
import useToken from "../store/token";
import notification from "../utils/notification";
import config from "../config";
import { Plus } from "@element-plus/icons-vue";

// TinyMCE imports
import "tinymce/tinymce";
import "tinymce/models/dom";
import "tinymce/themes/silver";
import "tinymce/icons/default";
import "tinymce/plugins/image";

const { token } = useToken();
const props = defineProps({
  id: { type: Number },
});
const emit = defineEmits(["success"]);

// Refs
const formRef = ref();
const uploadRef = ref();
const uploadAlbumRef = ref();
const editorRef = ref();
const fileList = ref([]);
const albumFileList = ref([]);
const categoryList = ref([]);
const albumDialogImageUrl = ref("");
const albumDialogVisible = ref(false);
const imageDialogVisible = ref(false);

// Replace direct uploadURL assignment with the wrapper
const uploadURL = uploadPictureURL();

// Form data
const form = reactive({
  id: props.id,
  name: "",
  categoryId: "",
  picture: "",
  stock: "",
  price: "",
  spec: "",
  description: "",
  albumList: [],
});

// Editor config
const initEditor = {
  width: "100%",
  skin_url: "/tinymce/skins/ui/oxide",
  content_css: "/tinymce/skins/content/default/content.css",
  language_url: "/tinymce/langs/zh-Hans.js",
  language: "zh-Hans",
  menubar: false,
  statusbar: false,
  toolbar: "bold underline italic strikethrough image undo redo",
  plugins: "image",
};

// Lifecycle hooks
onMounted(() => {
  loadGoods();
});

// Methods
const loadGoods = async () => {
  if (form.id) {
    const data = await getGoods({ id: form.id });
    const baseUrl = config.baseURL;

    if (data.picture) {
      fileList.value = [
        {
          name: data.picture.split("/").pop(),
          url: data.picture.startsWith(baseUrl)
            ? data.picture
            : `${baseUrl}${data.picture}`,
        },
      ];
    }

    if (data.albumList?.length) {
      albumFileList.value = data.albumList.map((item) => {
        const fullPicUrl = item.picture.startsWith(baseUrl)
          ? item.picture
          : `${baseUrl}${item.picture}`;
        return {
          name: fullPicUrl.split("/").pop(),
          url: fullPicUrl,
          uid: `${Date.now()}-${Math.random().toString(36).substring(2)}`,
        };
      });
      form.albumList = data.albumList.map((item) => item.picture);
    } else {
      albumFileList.value = [];
      form.albumList = [];
    }

    Object.assign(form, data);
  }

  const list = await getCategoryList();
  categoryList.value = arrayToTree(list);
};

const addSubmit = async () => {
  const data = {
    name: form.name,
    categoryId:7,
    price: form.price,
    picture: form.picture,
    stock: form.stock,
    spec: form.spec,
    description: form.description,
  };
  console.log(data);
  if (await addGoods(data)) {
    emit("success");
  }
};

function arrayToTree(items) {
  const itemMap = {};
  const result = [];

  items.forEach((item) => {
    itemMap[item.id] = { ...item, children: [] };
  });

  items.forEach((item) => {
    if (item.pid === 0) {
      result.push(itemMap[item.id]);
    } else {
      itemMap[item.pid].children.push(itemMap[item.id]);
    }
  });

  return result;
}

function handleExceed(files) {
  uploadRef.value.clearFiles();
  fileList.value = [files[0]];
  uploadRef.value.handleStart(files[0]);
  uploadRef.value.submit();
}

function btnCancel() {
  formRef.value.resetFields();
  form.picture = "";
  uploadRef.value.clearFiles();
  form.albumList = [];
  uploadAlbumRef.value.clearFiles();
  loadGoods();
}

function resetForm(id) {
  form.id = id;
  btnCancel();
}

async function editSubmit() {
  console.log("form:");
  console.log(form);
  const data = form.albumList == null ? {
    ...form
  } : {
    ...form,
    albumList: form.albumList.map((item) => {
      if (item.picture != null) {
        return item;
      } else {
        return { picture: item };
      }
    }),
  };

  console.log("data:");
  console.log(data);
  if (await editGoods(data)) {
    emit("success");
  }
}

// Upload handlers
function uploadSuccess(response) {
    console.log('上传响应：', response)
    
    // 处理XML格式的响应
    let errno, errmsg, data
    
    if (typeof response === 'string' && response.includes('APIResponse')) {
        // 解析XML字符串
        const parser = new DOMParser()
        const xmlDoc = parser.parseFromString(response, 'text/xml')
        
        errno = parseInt(xmlDoc.querySelector('errno')?.textContent || '-1')
        errmsg = xmlDoc.querySelector('errmsg')?.textContent || ''
        data = xmlDoc.querySelector('data')?.textContent || ''
    } else {
        // 如果不是XML格式，尝试正常解构
        ({ errno, errmsg, data } = response)
    }

    if (errno !== 0) {
        notification({ message: errmsg || '上传失败', type: "error" });
        return;
    }

    if (errmsg) {
        notification({ message: errmsg, type: "success" });
    }

    console.log("设置商品图片路径:", data);
    form.picture = data;
}

const uploadAlbumSuccess = (response) => {
    
    // 处理XML格式的响应
    let errno, errmsg, data
    
    if (typeof response === 'string' && response.includes('APIResponse')) {
        // 解析XML字符串
        const parser = new DOMParser()
        const xmlDoc = parser.parseFromString(response, 'text/xml')
        
        errno = parseInt(xmlDoc.querySelector('errno')?.textContent || '-1')
        errmsg = xmlDoc.querySelector('errmsg')?.textContent || ''
        data = xmlDoc.querySelector('data')?.textContent || ''
    } else {
        // 如果不是XML格式，尝试正常解构
        ({ errno, errmsg, data } = response)
    }

    if (errno !== 0) {
        notification({ message: errmsg || '上传失败', type: "error" });
        return;
    }

    if (errmsg) {
        notification({ message: errmsg, type: "success" });
    }

    if (!form.albumList) {
        form.albumList = [];
    }
    form.albumList = [...form.albumList, { picture: data }];
}

function albumHandleRemove(uploadFile) {
  albumFileList.value = albumFileList.value.filter(
    (file) => file.url !== uploadFile.url
  );
  form.albumList = albumFileList.value.map((file) => file.url);
}

function albumHandlePreview(uploadFile) {
  albumDialogImageUrl.value = uploadFile.url;
  albumDialogVisible.value = true;
}

// Editor handlers
function focusEditor() {
  editorRef.value?.focus();
}

function handleFormat(command) {
  document.execCommand(command, false, null);
  focusEditor();
  form.description = editorRef.value.innerHTML;
}

function handleUndo() {
  document.execCommand("undo", false, null);
  focusEditor();
  form.description = editorRef.value.innerHTML;
}

function handleRedo() {
  document.execCommand("redo", false, null);
  focusEditor();
  form.description = editorRef.value.innerHTML;
}

function handleInput() {
  form.description = editorRef.value.innerHTML;
}

function handleInsertImage() {
  imageDialogVisible.value = true;
}

defineExpose({ resetForm });
</script>

<style scoped>
.upload-demo {
  text-align: left;
  width: 91%;
}

.editor-content {
  border: 1px solid #dcdfe6;
  min-height: 200px;
  max-height: 400px;
  padding: 10px;
  margin-top: 10px;
  text-align: left;
  width: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  overflow-x: hidden;
  background-color: #fff;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
}

.editor-toolbar {
  margin-bottom: -10px;
  text-align: left;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  padding: 5px 10px;
  padding-bottom: 0;
  width: 100%;
  box-sizing: border-box;
}

.editor-toolbar .el-button {
  margin-right: 5px;
  padding: 5px 8px;
  border: none;
  background: transparent;
}

.editor-toolbar .el-button:hover {
  background-color: #e4e7ed;
}

.editor-content img {
  max-width: 100%;
  height: auto;
  margin: 5px 0;
}

.desc {
  margin-bottom: 20px;
}

.el-button-group {
  display: flex;
  align-items: center;
}

.el-button-group .el-button + .el-button {
  margin-left: -1px;
}
</style>